package com.bird.component.sensitive

import com.bird.component.lang.common.annotation.StringSensitive
import com.bird.component.lang.util.isnull
import com.bird.component.lang.util.nonnull
import com.fasterxml.jackson.databind.BeanDescription
import com.fasterxml.jackson.databind.SerializationConfig
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier

class StringSensitiveFieldModifier : BeanSerializerModifier() {
    override fun changeProperties(
        config: SerializationConfig?,
        beanDesc: BeanDescription?,
        beanProperties: MutableList<BeanPropertyWriter>
    ): List<BeanPropertyWriter> {
        return beanProperties
            .map {
                if (it.getAnnotation(StringSensitive::class.java)
                        .nonnull() && it.type.isTypeOrSubTypeOf(String::class.java)
                ) {
                    val stringSensitiveJsonSerializer = StringSensitiveJsonSerializer(it.serializer)
                    if (it.serializer.isnull()) {
                        it.assignSerializer(stringSensitiveJsonSerializer)
                    }
                }
                it
            }
    }
}